import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Hero } from './hero/hero'
import { HeroService } from './hero/hero.service'

@Component({
    selector: 'ng-heroes',
    template: `<h2>My Heroes</h2>
        <ul class="heroes">
            <li *ngFor="let hero of heroService.heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
              <span class="badge">{{hero.id}}</span> {{hero.name}}
            </li>
        </ul>
        <ul class="heroes">
            <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
              <span class="badge">{{hero.id}}</span> {{hero.name}}
            </li>
        </ul>
        <div *ngIf="selectedHero">
          <h2>
            {{selectedHero.name | uppercase}} is my hero
          </h2>
          <button (click)="gotoDetail()">View Details</button>
        </div>
        `
})
export class HeroComponent implements OnInit {
    heroes: Hero[] = [];
    oldTemplate = `<div *ngIf="selectedHero">
        <h2>{{selectedHero.name}} details!</h2>
        <div><label>id: </label>{{selectedHero.id}}</div>
        <div>
            <label>name: </label>
            <input [(ngModel)]="selectedHero.name" placeholder="name"/>
        </div>
        </div>`;
    selectedHero: Hero;

    constructor(private router: Router, public heroService: HeroService){}

    ngOnInit(){
        this.getHeroesAsync();
    }

    getHeroesAsync(){
        this.heroService.getHeroes().then(heroes => this.heroes = heroes);
    }

    onSelect(hero: Hero) {
        this.selectedHero = hero;
    }

    gotoDetail(): void {
        let link = ['/detail', this.selectedHero.id];
        this.router.navigate(link);
    }
}
